﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using VisionDesigner;
using VisionDesigner.EdgePairFlawInsp;
using VisionDesigner.PreproMask;
using VM.Common.Enums;
using VM.Common.EventMgrLib;
using VM.Common.Helper;
using VM.Dialogs.Views;
using VM.Start.Attributes;
using VM.Start.Common;
using VM.Start.Controls;
using VM.Start.Core;
using VM.Start.Events;
using VM.Start.Models;
using VM.Start.ViewModels;


namespace Plugin.Defect
{
    #region enum
    [Serializable]
    public enum eLinkCommand
    {
        InputImageLink,
        MathNum,
        PositionFix
    }

    [Serializable]
    public enum eOperateCommand
    {
        创建,
        载入,
        导出
    }

    [Serializable]
    public class TemplateModel : NotifyPropertyBase
    {
        [Newtonsoft.Json.JsonIgnore]
        // 模板的序号
        private int _index;
        [Newtonsoft.Json.JsonIgnore]
        public int Index
        {
            get => _index;
            set => Set(ref _index, value);
        }
        [Newtonsoft.Json.JsonIgnore]
        // 模板的名称
        private string _name;
        [Newtonsoft.Json.JsonIgnore]
        public string Name
        {
            get => _name;
            set => Set(ref _name, value);
        }

        public DefectEditViewModel Data { get; set; } // 模板数据

        // 标志是否已被销毁
        private bool _disposed = false;

        // 实现IDisposable接口
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this); // 防止重复释放
        }

        // 析构函数，防止未调用Dispose时资源泄露
        ~TemplateModel()
        {
            Dispose(false);
        }

        // Dispose模式，用于释放资源
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;

            if (disposing)
            {
                // 释放托管资源
                if (Data != null)
                {
                    Data.Dispose(); // 假设Data实现了IDisposable接口
                    Data = null;
                }
            }

            // 释放非托管资源（如果有）
            // ...

            _disposed = true;
        }
    }

    #endregion
    [Category("检测识别")]
    [DisplayName("缺陷检测")]
    [ModuleImageName("Defect")]
    [JsonObject(MemberSerialization.OptOut)]
    public class DefectViewModel : ModuleBase
    {

        #region  属性
        /// <summary>
        /// 匹配个数
        /// </summary>

        private LinkVarModel _MathNum = new LinkVarModel() { Value = 1 };
        public LinkVarModel MathNum
        {
            get { return _MathNum; }
            set { Set(ref _MathNum, value); }
        }

        /// UI界面绘制的缺陷框
        /// </summary>
        private List<CMvdRectangleF> _UIResToolFlawBoxList = new List<CMvdRectangleF>();
        /// <summary>
        /// UI界面绘制的卡尺框
        /// </summary>
        private List<CMvdRectangleF> _UIResToolCaliperList = new List<CMvdRectangleF>();

        /// <summary>
        /// UI界面绘制的边缘点
        /// </summary>
        private List<CMvdPointSetF> _UIResToolEdgeList = new List<CMvdPointSetF>();
        /// 掩膜图像
        /// </summary>
        private CPreproMaskTool _MaskImage = null;

        /// <summary>
        /// 绘制掩膜图形列表
        /// </summary>
        private List<CMvdShape> _MaskShapeList = new List<CMvdShape>();

        VisionDesigner.CMvdImage cPatternInputImg = null;





        public CEdgePairFlawInspTool _CEdgePairFlawInspTool = null;  // 缺陷检测算子
        private CEdgePairFlawInspTool cEdgePairFlawInspTool
        {
            get
            {
                try
                {

                    if (_CEdgePairFlawInspTool == null)
                    {
                        _CEdgePairFlawInspTool = new CEdgePairFlawInspTool();
                    }
                }
                catch (MvdException ex)
                {
                    if (ex.ErrorCode == MVD_ERROR_CODE.MVD_E_RUNTIME)
                    {
                        MessageView.Ins.MessageBoxShow("运行环境异常，请停止项目并检查加密狗！", eMsgType.Error);
                    }
                    else
                    {
                        MessageView.Ins.MessageBoxShow("创建实例失败！", eMsgType.Error);
                    }
                }
                return _CEdgePairFlawInspTool;
            }
        }

        public CEdgePairFlawPattern _EdgePairFlawPattern = null;             // 高精度模板算子

        /// <summary>
        /// 编辑模版Model
        /// </summary>
        private DefectEditViewModel _editViewModel;
        public DefectEditViewModel editViewModel
        {
            get
            {
                if (_editViewModel == null)
                {
                    _editViewModel = new DefectEditViewModel();
                }
                return _editViewModel;
            }
            set { Set(ref _editViewModel, value); }
        }

        /// <summary>
        /// 参数
        /// </summary>
        public ParamModel Param { get; set; } = new ParamModel();
        #endregion
        #region  数据接口


        [Newtonsoft.Json.JsonIgnore]
        public VMDisplayControl _MatchWindow;
        [Newtonsoft.Json.JsonIgnore]
        public VMDisplayControl MatchWindow
        {
            get
            {
                if (_MatchWindow == null)
                {
                    _MatchWindow = new VMDisplayControl();
                }
                return _MatchWindow;
            }
        }
        [Newtonsoft.Json.JsonIgnore]
        private ObservableCollection<TemplateModel> _templateList = new ObservableCollection<TemplateModel>();
        [Newtonsoft.Json.JsonIgnore]
        public ObservableCollection<TemplateModel> TemplateList
        {
            get { return _templateList; }
            set { _templateList = value; }
        }

        [Newtonsoft.Json.JsonIgnore]
        public TemplateModel _selectedTemplate;
        public TemplateModel SelectedTemplate
        {
            get { return _selectedTemplate; }
            set
            {
                Set(ref _selectedTemplate, value);
                if (_selectedTemplate != null)
                {
                    editViewModel = _selectedTemplate.Data;
                    //  MatchWindow.Copy(editViewModel.TemplateWindow);
                    _EdgePairFlawPattern = editViewModel.EdgePairFlawPattern;
                }
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private ObservableCollection<ResultTemplateMatch> _ResultTemplateMatchs;
        [Newtonsoft.Json.JsonIgnore]
        public ObservableCollection<ResultTemplateMatch> ResultTemplateMatchs
        {
            get
            {
                if (_ResultTemplateMatchs == null)
                {
                    _ResultTemplateMatchs = new ObservableCollection<ResultTemplateMatch>();
                }
                return _ResultTemplateMatchs;
            }
            set { _ResultTemplateMatchs = value; }
        }

        /// <summary>
        /// ROI
        /// </summary>
        private ROITypeEnum _ROIType = ROITypeEnum.全图;
        public ROITypeEnum ROIType
        {
            get { return _ROIType; }
            set
            {
                Set(ref _ROIType, value, new Action(() =>
                {
                    switch (_ROIType)
                    {
                        case ROITypeEnum.全图:
                            mWindowH.ROIType = ROITypeEnum.全图;
                            break;
                        case ROITypeEnum.矩形:
                            mWindowH.ROIType = ROITypeEnum.矩形;
                            break;
                        case ROITypeEnum.圆:
                            mWindowH.ROIType = ROITypeEnum.圆;
                            break;
                        default:
                            break;
                    }
                }));
            }
        }

        #endregion
        #region  指令

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _LinkCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase LinkCommand
        {
            get
            {
                if (_LinkCommand == null)
                {
                    //以GUID+类名作为筛选器
                    EventMgr.Ins
                        .GetEvent<VarChangedEvent>()
                        .Subscribe(OnVarChanged, o => o.SendName.StartsWith($"{ModuleGuid}"));
                    _LinkCommand = new CommandBase(
                        (obj) =>
                        {
                            eLinkCommand linkCommand = (eLinkCommand)obj;
                            switch (linkCommand)
                            {
                                case eLinkCommand.InputImageLink:
                                    CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "Image");
                                    EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},InputImageLink");
                                    break;
                                case eLinkCommand.PositionFix:
                                    CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "CPositionFixTool");
                                    EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},PositionFix");
                                    break;
                                case eLinkCommand.MathNum:
                                    CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "int");
                                    EventMgr.Ins.GetEvent<OpenVarLinkViewEvent>().Publish($"{ModuleGuid},MathNumLink");
                                    break;
                                default:
                                    break;
                            }
                        }
                    );
                }
                return _LinkCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _OperateCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase OperateCommand
        {
            get
            {
                if (_OperateCommand == null)
                {
                    _OperateCommand = new CommandBase(
                        (obj) =>
                        {
                            try
                            {
                                eOperateCommand par = (eOperateCommand)obj;
                                switch (par)
                                {
                                    case eOperateCommand.创建:
                                        try
                                        {
                                            editViewModel = new DefectEditViewModel();
                                            DefectEditView editView = new DefectEditView
                                            {
                                                DataContext = editViewModel
                                            };
                                            editViewModel.view = editView;
                                            editViewModel.LocalImage = DispImage;
                                            editViewModel.matchingViewModel = this;
                                            _EdgePairFlawPattern = new CEdgePairFlawPattern();
                                            editViewModel.EdgePairFlawPattern = this._EdgePairFlawPattern;
                                            var view = this.ModuleView as DefectView;
                                            editView.Owner = view;
                                            editViewModel.Loaded();
                                            editView.ShowDialog();
                                        }
                                        catch (MvdException ex)
                                        {
                                            if (ex.ErrorCode == MVD_ERROR_CODE.MVD_E_RUNTIME)
                                            {
                                                MessageView.Ins.MessageBoxShow("运行环境异常，请停止项目并检查加密狗！", eMsgType.Error);
                                            }
                                            else
                                            {
                                                MessageView.Ins.MessageBoxShow("创建实例失败！", eMsgType.Error);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageView.Ins.MessageBoxShow($"创建操作失败: {ex.Message}", eMsgType.Error);
                                        }
                                        break;
                                    case eOperateCommand.载入:
                                        try
                                        {
                                            OpenFileDialog fileDlg = new OpenFileDialog
                                            {
                                                Filter = "XML Files|*.epmxml;*.xml",
                                                FilterIndex = 2,
                                                RestoreDirectory = true
                                            };
                                            if (fileDlg.ShowDialog() == true) // WPF的对话框返回bool
                                            {
                                                string filePath = fileDlg.FileName;
                                                string Name = Path.GetFileNameWithoutExtension(filePath);
                                                if (File.Exists(filePath))
                                                {
                                                    CEdgePairFlawPattern cEdgePairFlawPattern = new CEdgePairFlawPattern();
                                                    cEdgePairFlawPattern.ImportPattern(filePath);

                                                    DefectEditViewModel editVModel = new DefectEditViewModel();
                                                    editViewModel = editVModel;
                                                    editViewModel.EdgePairFlawPattern = cEdgePairFlawPattern;
                                                    _EdgePairFlawPattern = cEdgePairFlawPattern;
                                                    TemplateModel templateData = new TemplateModel();
                                                    templateData.Name = Name;
                                                    templateData.Index = TemplateList.Count;
                                                    templateData.Data = editViewModel;
                                                    TemplateList.Add(templateData);
                                                    SelectedTemplate = templateData;




                                                }
                                            }
                                        }
                                        catch (MvdException ex)
                                        {
                                            MessageView.Ins.MessageBoxShow($"导入XML文件失败. 错误码: 0x{ex.ErrorCode:X}, 信息: {ex.Message}", eMsgType.Error);
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageView.Ins.MessageBoxShow($"导入XML文件失败: {ex.Message}", eMsgType.Error);
                                        }
                                        break;
                                    case eOperateCommand.导出:
                                        if (_EdgePairFlawPattern == null)
                                        {
                                            MessageView.Ins.MessageBoxShow("当前模板没有数据！导出失败！", eMsgType.Error);
                                            return;
                                        }
                                        else if (_EdgePairFlawPattern.Result.Data != null && _EdgePairFlawPattern.Result == null && (_EdgePairFlawPattern.InputImage == null || _EdgePairFlawPattern.InputImage.IsEmpty))
                                        {
                                            if (SelectedTemplate.Data.TrainImage == null && SelectedTemplate.Data.TrainImage.IsEmpty)
                                            {
                                                MessageView.Ins.MessageBoxShow("当前模板没有训练图像！导出失败！", eMsgType.Error);
                                                return;
                                            }
                                            _EdgePairFlawPattern.InputImage = SelectedTemplate.Data.TrainImage;
                                            _EdgePairFlawPattern.Train();
                                        }
                                        try
                                        {
                                            SaveFileDialog fileDlg = new SaveFileDialog
                                            {
                                                Filter = "XML Files|*.epmxml",
                                                RestoreDirectory = true,
                                                FileName = SelectedTemplate?.Name ?? "NewTemplate"  // 防止 SelectedTemplate 为 null
                                            };
                                            if (fileDlg.ShowDialog() == true) // WPF的对话框返回bool
                                            {
                                                string filePath = fileDlg.FileName;
                                                _EdgePairFlawPattern.ExportPattern(filePath);
                                            }
                                        }
                                        catch (MvdException ex)
                                        {
                                            MessageView.Ins.MessageBoxShow($"导出模型文件失败. 错误码: 0x{ex.ErrorCode:X}, 信息: {ex.Message}", eMsgType.Error);
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageView.Ins.MessageBoxShow($"导出模型文件失败: {ex.Message}", eMsgType.Error);
                                        }
                                        break;
                                    default:
                                        throw new ArgumentOutOfRangeException();
                                }
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    );
                }
                return _OperateCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ExecuteCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ExecuteCommand
        {
            get
            {
                if (_ExecuteCommand == null)
                {
                    _ExecuteCommand = new CommandBase(
                        (obj) =>
                        {
                            ExeModule();
                        }
                    );
                }
                return _ExecuteCommand;
            }
        }

        [Newtonsoft.Json.JsonIgnore]
        private CommandBase _ConfirmCommand;
        [Newtonsoft.Json.JsonIgnore]
        public CommandBase ConfirmCommand
        {
            get
            {
                if (_ConfirmCommand == null)
                {
                    _ConfirmCommand = new CommandBase(
                        (obj) =>
                        {
                            var view = this.ModuleView as DefectView;
                            if (view != null)
                            {
                                view.Close();
                            }
                        }
                    );
                }
                return _ConfirmCommand;
            }
        }

        #endregion
        #region  方法
        public override void Loaded()
        {
            base.Loaded();
            var view = ModuleView as DefectView;
            if (view != null)
            {
                ClosedView = true;
                if (DispImage == null)
                {
                    SetDefaultLink();
                    if (InputImageLinkText == null) return;
                }
                GetDispImage(InputImageLinkText, true);
                foreach (var item in TemplateList)
                {
                    item.Data.Loaded();
                }
                var matchingItem = TemplateList.FirstOrDefault(item => item.Name == SelectedTemplate.Name && item.Index == SelectedTemplate.Index);
                SelectedTemplate = matchingItem;

            }

        }

        public override void SetDefaultLink()
        {
            if (InputImageLinkText == null)
            {
                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "Image");
                var moduls = VarLinkViewModel.Ins.Modules.LastOrDefault();
                if (moduls?.VarModels.Count > 0)
                {
                    InputImageLinkText = $"&{moduls.DisplayName}.{moduls.VarModels[0].Name}";
                }
            }

            if (PositionFixText == null)
            {
                CommonMethods.GetModuleList(ModuleParam, VarLinkViewModel.Ins.Modules, "CPositionFixTool");
                var moduls = VarLinkViewModel.Ins.Modules.LastOrDefault();
                if (moduls?.VarModels.Count > 0)
                {
                    PositionFixText = $"&{moduls.DisplayName}.{moduls.VarModels[0].Name}";
                }
            }
        }

        private void OnVarChanged(VarChangedEventParamModel obj)
        {
            switch (obj.SendName.Split(',')[1])
            {
                case "InputImageLink":
                    InputImageLinkText = obj.LinkName;
                    if (InputImageLinkText == null) return;
                    GetDispImage(InputImageLinkText, true);
                    break;
                case "PositionFix":
                    PositionFixText = obj.LinkName;
                    if (PositionFixText == null) return;
                    GetPositionFix(PositionFixText);
                    break;
                case "MathNumLink":
                    MathNum.Text = obj.LinkName;
                    break;
                default:
                    break;
            }
        }

        public override bool ExeModule()
        {
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    mWindowH.Clear();
                    if (InputImageLinkText != null)
                    {
                        GetDispImage(InputImageLinkText, true);
                    }
                    else
                    {
                        SetDefaultLink();
                    }
                    ResultTemplateMatchs.Clear();
                });

                if ((null == cEdgePairFlawInspTool) || (null == cEdgePairFlawInspTool) ||
                    (null == DispImage) || (_EdgePairFlawPattern == null) || (this._EdgePairFlawPattern.Result == null))
                // || (_EdgePairFlawPattern.Result == null)
                {
                    ChangeModuleRunStatus(eRunStatus.NG);
                    return false;
                }
                if (DispImage.IsEmpty)
                {
                    ChangeModuleRunStatus(eRunStatus.NG);
                    return false;
                }
                cEdgePairFlawInspTool.InputImage = DispImage;
                // cEdgePairFlawInspTool.Pattern =  editViewModel.EdgePairFlawPattern.Result.Data;
                cEdgePairFlawInspTool.Pattern = this._EdgePairFlawPattern.Result.Data;
                if (_MaskShapeList.Count > 0)
                {
                    if (editViewModel.m_bNeedUpdateMaskImg)
                    {
                        _MaskImage.InputImage = DispImage;
                        _MaskImage.RegionList.Clear();
                        foreach (var item in _MaskShapeList)
                        {
                            _MaskImage.RegionList.Add(new Tuple<CMvdShape, bool>(item, false));
                        }
                        _MaskImage.Run();

                        cEdgePairFlawInspTool.MaskImage = _MaskImage.OutputImage;
                    }
                    editViewModel.m_bNeedUpdateMaskImg = false;
                }
                else
                {
                    cEdgePairFlawInspTool.MaskImage = null;
                }
                editViewModel.m_bNeedUpdateMaskImg = false;
                //ClearCaliper();
                // ClearEdges();
                // ClearFlawBox();
                // 设置使能边缘对中点
                cEdgePairFlawInspTool.BasicParam.ShowEdgeMidPointStatus = true;
                Stopwatch.Restart();
                Param.UpdateParam(cEdgePairFlawInspTool);

                cEdgePairFlawInspTool.Run();
                DrawCaliper(cEdgePairFlawInspTool.Result.CaliperBoxList);
                DrawEdge(cEdgePairFlawInspTool.Result.Edge0PointList);
                DrawEdge(cEdgePairFlawInspTool.Result.Edge1PointList);
                //渲染轮廓框
                foreach (var item in cEdgePairFlawInspTool.Result.FlawInfoList)
                {
                    DrawFlawBox(item.FlawBox);
                }

                if (cEdgePairFlawInspTool.Result == null)
                {
                    ChangeModuleRunStatus(eRunStatus.NG);
                    return false;
                }

                ChangeModuleRunStatus(eRunStatus.OK);

                CommonMethods.UIAsync(() =>
                {
                    int i = 1;
                    foreach (var item in cEdgePairFlawInspTool.Result.FlawInfoList)
                    {
                        ResultTemplateMatchs.Add(
                           new ResultTemplateMatch()
                           {
                               ID = i,

                               Width = item.FlawBox.Width,
                               Height = item.FlawBox.Height,
                               X = item.FlawBox.CenterX,
                               Y = item.FlawBox.CenterY,
                               Angle = item.FlawBox.Angle,

                           }
                          );
                        i++;
                    }
                });
                return true;
            }
            catch
            {
                ChangeModuleRunStatus(eRunStatus.NG);
                return false;
            }
        }

        public override bool ExeModule(string TemplateName)
        {
            return ExeModule();
        }

        public override void AddOutputParams()
        {
            base.AddOutputParams();
            if (cEdgePairFlawInspTool != null && cEdgePairFlawInspTool.Result != null && cEdgePairFlawInspTool.Result.FlawInfoList.Count > 0)


            {
                AddOutputParam("缺陷数", "int", cEdgePairFlawInspTool.Result.FlawInfoList.Count);
                foreach (var item in cEdgePairFlawInspTool.Result.FlawInfoList)
                {
                    AddOutputParam("中心x", "double", item.FlawBox.CenterX);
                    AddOutputParam("中心y", "double", item.FlawBox.CenterY);
                    AddOutputParam("长", "double", item.FlawBox.Height);
                    AddOutputParam("宽", "double", item.FlawBox.Width);
                    AddOutputParam("角度", "double", item.FlawBox.Angle);
                }

            }
            else
            {
                AddOutputParam("中心y", "int", 0);
                AddOutputParam("长", "MatchPoint", null);
                AddOutputParam("宽", "MatchPointX", null);
                AddOutputParam("角度", "MatchPointY", null);
                AddOutputParam("匹配角度", "MatchAngle", null);
                AddOutputParam("匹配X方向尺度", "MatchXScale", null);
                AddOutputParam("匹配Y方向尺度", "MatchYScale", null);
            }
        }

        #endregion

        private void DrawFlawBox(CMvdRectangleF resFlawBox)
        {
            try
            {
                var newItem = resFlawBox.Clone() as CMvdRectangleF;
                newItem.BorderColor = new MVD_COLOR(255, 0, 0, 255);
                mWindowH.AddShape(newItem);
                _UIResToolFlawBoxList.Add(newItem);
            }
            finally
            {
                mWindowH.MVDRender.Display();
            }
        }
        /// 渲染轮廓点
        /// </summary>
        /// <param name="resEdgePointList"></param>
        private void DrawEdge(List<Tuple<MVD_POINT_F, Int32>> resEdgePointList)
        {
            try
            {
                var _SuccPointSetF = new CMvdPointSetF();
                var _ErrPointSetF = new CMvdPointSetF();
                foreach (var item in resEdgePointList)
                {
                    if (0 == item.Item2)
                    {
                        _SuccPointSetF.AddPoint(item.Item1.fX, item.Item1.fY);
                    }
                    else if (1 == item.Item2)
                    {
                        _ErrPointSetF.AddPoint(item.Item1.fX, item.Item1.fY);
                    }
                }

                if (0 != _SuccPointSetF.PointsList.Count)
                {
                    _SuccPointSetF.BorderColor = new MVD_COLOR(0, 255, 0, 255);
                    mWindowH.AddShape(_SuccPointSetF);
                    _UIResToolEdgeList.Add(_SuccPointSetF);
                }

                if (0 != _ErrPointSetF.PointsList.Count)
                {
                    _ErrPointSetF.BorderColor = new MVD_COLOR(255, 0, 0, 255);
                    mWindowH.AddShape(_ErrPointSetF);
                    _UIResToolEdgeList.Add(_ErrPointSetF);
                }
            }
            finally
            {
                mWindowH.MVDRender.Display();
            }
        }


        //渲染卡尺 

        public void DrawCaliper(List<CMvdRectangleF> resCaliperBoxList)
        {
            try
            {
                foreach (var item in resCaliperBoxList)
                {
                    var newItem = item.Clone() as CMvdRectangleF;
                    newItem.BorderColor = new MVD_COLOR(0, 0, 255, 255);
                    mWindowH.AddShape(newItem);
                    _UIResToolCaliperList.Add(newItem);
                }
            }
            finally
            {
                mWindowH.MVDRender.Display();
            }
        }

    }
}
